import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token'
// import Login from '@/views/Longin'
// import Layout from '@/views/Layout'
// import Home from '@/views/Home'
// import User from '@/views/User'
// import Search from '@/views/Search'
// import SearchResult from '@/views/Search/SearchResult'
// import ArticleDetail from '@/views/ArticleDetail'
// import UserEdit from '@/views/User/UserEdit'
// import Chat from '@/views/Chat'
Vue.use(VueRouter)
// 路由懒加载：为了让第一个页面，加载的app.js小一点，打开页面快一点
const routes = [
  {
    path: '/',
    redirect: '/layout/home' // 默认显示layout和layout下首页
  },
  {
    path: '/login',
    component: () => import(/* webpackChunkName: "Login " */'@/views/Longin'),
    beforeEnter: (to, from, next) => {
      // ...
      if (getToken()?.length > 0) {
        // next(false)// 留在原地
        next('/layout/home')
      } else {
        next()// 通通放行
      }
    }
  },
  {
    path: '/layout',
    component: () => import(/* webpackChunkName: "Layout " */'@/views/Layout'),
    // redirect: '/layout/home',
    children: [
      {
        path: 'home',
        component: () => import(/* webpackChunkName: "Home " */'@/views/Home'),
        meta: {
          scrollT: 0// 保存首页离开时滚动条的位置
        }
      },
      {
        path: 'user',
        component: () => import(/* webpackChunkName: "User " */'@/views/User')
      }
    ]
  },
  {
    path: '/search',
    component: () => import(/* webpackChunkName: "Search " */ '@/views/Search')
  },
  { // 搜索结果页面
    path: '/search_result/:kw',
    component: () => import(/* webpackChunkName: "SearchResult " */'@/views/Search/SearchResult')
  },
  { // 文章详情页
    path: '/detail',
    component: () => import(/* webpackChunkName: "Detail " */'@/views/ArticleDetail')
  },
  // 编辑用户资料页面
  {
    path: '/user_edit',
    component: () => import(/* webpackChunkName: "UserEdit " */'@/views/User/UserEdit')
  },
  // 聊天页面
  {
    path: '/chat',
    component: () => import(/* webpackChunkName: "Chat " */'@/views/Chat')
  }
]

const router = new VueRouter({
  routes
})
// 路由-全局前置守卫，在路由发生真正跳转之前，执行此函数，可以决定路由是否跳转/取消/强制终止，切换别的路由
// router.beforeEach((to, from, next) => {
//   // 如果已经登录 不要登录到登录页面
//   if (getToken()?.length > 0 && to.path === '/login') {
//     next(false)// 留在原地
// next('/layout/home')
//   } else {
//     next()// 通通放行
//   }
// })

export default router
